package com.sailors.common.task.provider.infra.system.config.task;

import lombok.Data;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * 任务延时队列
 *
 * @description:
 * @author: cyj
 * @date 2022 -11-23 14:42:02
 */
@Data
public class CommonDelayQueueTask<T> implements Delayed {

    /**
     * Param 延时后执行consumer参数
     */
    private T param;

    /**
     * 延时后执行consumer.accept
     */
    private Consumer<T> consumer;

    /**
     * Delay time
     */
    private long delayTime;

    /**
     * Common delay queue
     *
     * @param param     param
     * @param delayTime delay time
     * @param consumer  consumer
     */
    public CommonDelayQueueTask(T param, long delayTime, Consumer<T> consumer) {
        this.param = param;
        // 延迟时间加当前时间
        this.delayTime = System.currentTimeMillis() + delayTime;
        // 延时后执行业务
        this.consumer = consumer;
    }

    // 获取任务剩余时间
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(delayTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return Long.compare(delayTime, ((CommonDelayQueueTask) o).delayTime);
    }
}
